<script setup>
import { ref, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  uploadFile,
  getUsersuploadedFiles,
  deleteFile,
  getSubmittedUsers,
  downloadFile,
} from "@/utils/api/File.js";
import FilePreviewModal from "@/a-components/less/FilePreviewModal.vue";
import JSZip from "jszip";
import { saveAs } from "file-saver"; // 用于保存文件
import { previewFile } from "@/utils/api/File.js";

// 获取路由实例
const router = useRouter();
// 获取用户角色
const userInfo = JSON.parse(localStorage.getItem("userInfo")) || {};
const userRole = userInfo.userRole || "user"; // 默认是普通用户

// 选项管理
const activeTab = ref("upload"); // 当前选中的书签
const uploadProgress = ref(0); // 上传进度
const uploadedFiles = ref([]); // 存储上传成功的文件

const submittedUsersList = ref([]); // 存储所有用户投稿信息

const selectedDownloadFiles = ref([]); // 选中的用户投稿文件
const selectedPreviewFileId = ref(""); // 预览的文件
const selectedUsers = ref([]); // 管理员表格多选

// 管理员查看用户投稿时的弹窗状态
const userDialogVisible = ref(false);
const currentUserFiles = ref([]);
const currentUserName = ref("");

const key = "userInfo";

const previewModal = ref(null);

//加载所有投稿用户信息
const loadUserSubmissions = async () => {
  const usersList = await getSubmittedUsers();
  if (usersList.length > 0) {
    submittedUsersList.value = usersList;
  } else {
    submittedUsersList.value = [];
    ElMessage.info("暂无投稿用户");
  }
};

// 加载用户上传的文件列表
const loadUsersFileList = async () => {
  const userId = JSON.parse(localStorage.getItem(key)).id;
  const uploadedFilesBuf = await getUsersuploadedFiles(userId);
  console.log(uploadedFilesBuf);
  if (uploadedFilesBuf.length > 0) {
    const uploadedFileNameBuf = uploadedFilesBuf;
    uploadedFiles.value = uploadedFileNameBuf;
  } else {
    uploadedFiles.value = [];
    ElMessage.info("您还未上传任何文件");
  }
};

// 处理上传
const handleUpload = async (params) => {
  console.log(params.file);
  const file = params.file;
  const allowedTypes = [
    "image/jpeg",
    "image/png",
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "text/plain",
    "video/mp4",
    "video/quicktime",
    "video/x-msvideo",
  ];

  if (!allowedTypes.includes(file.type)) {
    ElMessage.error("不支持该文件类型");
    return false;
  } else if (file.size > 500 * 1024 * 1024) {
    ElMessage.error("文件大小不能超过 500MB");
    return false;
  }

  try {
    uploadProgress.value = 0; // 初始化进度条

    // 调用封装的 `uploadFile` 方法，并监听上传进度
    const response = await uploadFile(file, (progress) => {
      uploadProgress.value = progress;
    });

    if (response != null) {
      handleUploadSuccess(file);
    } else {
      ElMessage.error(response.message || "上传失败");
    }
  } catch (error) {
    console.error("上传失败：", error);
    ElMessage.error("上传失败，请稍后重试");
  }
};

// 处理上传成功
const handleUploadSuccess = (file) => {
  loadUsersFileList();
  ElMessage.success(`${file.name} 上传成功`);
};

// 删除文件
const confirmDelete = (file) => {
  ElMessageBox.confirm(`确定要删除文件 "${file.fileName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteSelectedFile(file);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const deleteSelectedFile = async (file) => {
  try {
    await deleteFile(file.id); // 发送 DELETE 请求
    loadUsersFileList(); // 重新加载文件列表
    ElMessage.success(`文件 "${file.fileName}" 已删除`);
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

// 选择用户查看投稿
const selectUser = (user) => {
  currentUserName.value = user.username;
  currentUserFiles.value = user.files;
  userDialogVisible.value = true;
};

const previewVisible = ref(false);
//预览文件
const openPreviewFile = (fileId) => {
  previewVisible.value = true;
  selectedPreviewFileId.value = fileId;
  console.log("preview file");
};

// 批量下载
const downloadSelectedFiles = async () => {
  const usersNum = selectedUsers.value.length;
  const filesToDownload = selectedUsers.value.flatMap((user) => user.files);
  console.log(selectedUsers.value);

  if (usersNum === 0) {
    ElMessage.warning("请选择要下载的文件");
    return;
  }

  ElMessage.success(
    `开始批量下载：共有 ${usersNum} 个用户的 ${filesToDownload.length} 个文件`
  );

  // 创建一个 JSZip 实例
  const zip = new JSZip();

  // 遍历每个用户的文件，创建以用户名为文件名的压缩包
  for (const user of selectedUsers.value) {
    const userZip = zip.folder(user.username); // 创建一个以用户名为名的文件夹

    // 遍历该用户的文件
    for (const file of user.files) {
      try {
        const response = await previewFile(file.id);
        // const fileUrl = URL.createObjectURL(response.data, {type: 'charset=utf-8'}); // 创建一个 URL 对象
        // console.log(fileUrl);
        const fileContent = new Blob([response.data]); // 获取文件的二进制数据
        const fileName = decodeURIComponent(file.fileName); // 解码文件名，避免乱码

        // 将文件添加到该用户的文件夹中
        userZip.file(fileName, fileContent);
      } catch (error) {
        console.error(`下载用户 ${user.username} 文件失败`, error);
      }
    }
  }

  // 生成并下载压缩包
  try {
    const content = await zip.generateAsync({ type: "blob" }); // 生成压缩包
    const currentDate = new Date();

    // 格式化日期和时间（YYYY-MM-DD_HH-MM-SS）
    const formattedDate = `${currentDate.getFullYear()}-${(
      currentDate.getMonth() + 1
    )
      .toString()
      .padStart(2, "0")}-${currentDate.getDate().toString().padStart(2, "0")}`;
    const formattedTime = `${currentDate
      .getHours()
      .toString()
      .padStart(2, "0")}-${currentDate
      .getMinutes()
      .toString()
      .padStart(2, "0")}-${currentDate
      .getSeconds()
      .toString()
      .padStart(2, "0")}`;

    const fileName = `投稿文件_${formattedDate}_${formattedTime}.zip`;
    saveAs(content, fileName);

    ElMessage.success("批量下载完成");
  } catch (error) {
    ElMessage.error("批量下载失败");
    console.error("生成压缩包失败", error);
  }
};

// 下载单个文件
const downloadSingleFile = (file) => {
  downloadFile(file.id)
    .then((response) => {
      const Disposition = response.headers["content-disposition"];
      console.log(Disposition);
      // 创建一个 URL 来下载文件
      const contentDisposition = response.headers["content-disposition"];
      const fileName = decodeURIComponent(
        contentDisposition
          ? contentDisposition.split('filename="')[1].split('"')[0]
          : "downloaded_file"
      ); // 获取文件名（如果有的话）

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName); // 设置下载文件的文件名
      document.body.appendChild(link);
      link.click(); // 模拟点击下载
      document.body.removeChild(link); // 清除临时元素
      ElMessage.success(`下载文件：${file.fileName}`);
    })
    .catch((error) => {
      console.error("File download failed", error);
      ElMessage.error("下载失败");
    });

  // TODO: 处理文件下载逻辑
};
// 跳转到主页
const goHome = () => {
  router.push("/");
};

watch(activeTab, (newVal) => {
  if (newVal === "list") {
    loadUserSubmissions();
  } else {
    loadUsersFileList();
  }
});

onMounted(async () => {
  //用户已上传文件加载
  await loadUsersFileList();
});
</script>

<template>
  <div class="container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <!-- 返回主页按钮 -->
      <div class="back-home">
        <el-button @click="goHome" type="text">< 返回主页</el-button>
      </div>
      <el-button
        class="tab-button"
        :type="activeTab === 'upload' ? 'primary' : 'default'"
        @click="activeTab = 'upload'"
        size="large"
        round
      >
        用户投稿
      </el-button>
      <el-button
        v-if="userRole === 'admin'"
        class="tab-button"
        :type="activeTab === 'list' ? 'primary' : 'default'"
        @click="activeTab = 'list'"
        size="large"
        round
      >
        投稿列表
      </el-button>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content">
      <!-- 用户投稿 -->
      <el-card v-if="activeTab === 'upload'" class="upload-section">
        <h3>上传文件</h3>
        <el-upload
          class="upload-box"
          drag
          action="#"
          multiple
          :http-request="handleUpload"
          :auto-upload="true"
          :show-file-list="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽文件到这里 或 <em>点击上传</em></div>
        </el-upload>

        <!-- 上传须知 -->
        <el-alert title="请注意：" type="info" :closable="false" class="notice">
          <ul>
            <li>
              支持的文件格式：JPG、JPEG、PNG、PDF、DOCX、TXT、MP4、MOV、AVI
            </li>
            <li>单个文件最大支持 500MB</li>
            <li>请勿上传包含敏感信息的文件</li>
          </ul>
        </el-alert>

        <!-- 上传进度条 -->
        <el-progress
          v-if="uploadProgress > 0 && uploadProgress < 100"
          :percentage="uploadProgress"
          class="upload-progress"
        />

        <!-- 上传成功的文件列表 -->
        <el-card v-if="uploadedFiles.length" class="file-list">
          <h3>上传成功的文件：</h3>
          <el-tag
            v-for="file in uploadedFiles"
            :key="file"
            class="file-tag"
            type="success"
            closable
            @close="confirmDelete(file)"
          >
            {{ file.fileName }}
          </el-tag>
        </el-card>
      </el-card>

      <!-- 管理员查看投稿列表 -->
      <el-card v-if="activeTab === 'list'" class="list-section">
        <h3>所有投稿用户</h3>
        <el-table
          :data="submittedUsersList"
          style="width: 100%; max-height: 50vh; overflow-y: auto"
          border
          @selection-change="(val) => (selectedUsers = val)"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户姓名">
            <template #default="{ row }">
              <el-button type="text" @click="selectUser(row)">
                {{ row.username }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="文件数">
            <template #default="{ row }">
              {{ row.files.length }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量下载按钮 -->
        <div class="batch-download">
          <el-button type="primary" @click="downloadSelectedFiles">
            批量下载
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 管理员查看用户投稿的弹窗 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="`${currentUserName} 的投稿文件`"
    >
      <el-table :data="currentUserFiles.map((file) => ({ file }))" border>
        <el-table-column prop="file" label="文件名">
          <template #default="{ row }">
            {{ row.file.fileName }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              @click="openPreviewFile(row.file.id)"
            >
              预览
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="downloadSingleFile(row.file)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 预览弹窗 -->
    <FilePreviewModal
      :visible="previewVisible"
      :file-id="selectedPreviewFileId"
      @close="() => (previewVisible = false)"
    />
  </div>
</template>

<style scoped>
.container {
  display: flex;
  height: 70vh;
  background-color: #f8f9fa;
}

/* 侧边栏 */
.sidebar {
  width: 140px;
  background: #2c3e50;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.tab-button {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  margin-top: 15px;
  width: 100%;
  margin-left: 0;
}

/* 右侧内容 */
.content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  overflow-y: auto;
}

.upload-section,
.list-section {
  width: 95%;
  padding: 20px;
  height: 65vh;
}

/* 上传区域 */
.upload-box {
  width: 100%;
  margin-top: 15px;
}

/* 提示框 */
.notice {
  margin-top: 15px;
}

/* 上传文件列表 */
.file-list {
  margin-top: 15px;
  padding: 10px;
}

/* 文件标签 */
.file-tag {
  margin: 5px;
  font-size: 14px;
}

/* 投稿列表 */
.batch-download {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.back-home {
  margin: 0px;
}
</style>
